<template>
  <div class="app-container">
    <!-- 搜索框展示 -->
    <el-row class="content">
      <el-col :span="12" class="top-content">
        <div class="search-group">
          <span class="search-label">难易程度：</span>
          <el-select class="search-item" v-model="difficulty" size="mini">
            <el-option label="简单" value="1"></el-option>
            <el-option label="容易" value="2"></el-option>
            <el-option label="适中" value="3"></el-option>
            <el-option label="困难" value="4"></el-option>
            <el-option label="极难" value="5"></el-option>
          </el-select>
        </div>
        <div class="search-group">
          <span class="search-label">选择章节：</span>
          <el-select class="search-item2" v-model="fk_t_sctk_chapter_id" placeholder="选择章节" size="mini">
            <el-option v-for="item in flatChapters" :key="item.id" :label="item.name" :value="item.id">
              <span :style="{ paddingLeft: item.level * 20 + 'px' }">{{ item.name }}</span>
            </el-option>

          </el-select>
          <el-switch v-model="chapterCheck" active-text="章节检测" style="margin-left: 10px; margin-top: 8px;"></el-switch>
        </div>

        <div class="action-buttons-wrapper ">
          <el-button type="success" @click="editChapter" size="mini">编辑章节</el-button>
          <el-button type="primary" @click="handleAddQuestion" size="mini  " class="import-button">
            导入试题
          </el-button>
        </div>

      </el-col>
    </el-row>
    <div class="main-content">
      <!-- 输入区 -->
      <div class="input-area">


        <div class="toolbar">输入区：
          <div class=" toolbar-separator">
            <!-- <el-button type="text" @click="formatExample">格式案例说明</el-button> -->
            <!-- <el-button type="text" @click="videoTutorial">视频教程</el-button> -->
            <el-button type="text" @click="clearInput">清空</el-button>
            <el-button type="text" @click="autoFormat">自动识别格式</el-button>
          </div>

        </div>

        <div class="editable-container">
          <!-- 占位符 -->
          <div v-if="isPlaceholderVisible" class="placeholder-text">{{ placeholderText }}</div>

          <!-- 可编辑区域 -->
          <div contentEditable="true" class="editable-div scrollable-input" @input="handleInput" ref="editableDiv">
          </div>
        </div>
      </div>

      <!-- 检查区 -->
      <div class="input-area">

        <div class="toolbar">检查区：
          <!-- <div class=" toolbar-span ">
            总计输入题数：1
          </div> -->
          <div class="toolbar-separator">
            <!-- <el-button type="text" style="color: #333; font-size: 10px;">总计输入 1 道 单选题 1 道</el-button> -->
            <el-button type="text" style="color: #666; font-size: 14px;">
              总题数：{{ totalQuestions }} 道 |
              <span v-if="errorQuestionCount > 0" style="color: red;">
                错误题目：{{ errorQuestionCount }} 道
              </span>
              <span v-if="errorQuestionCount > 1" style="margin-left: 10px;">
                第 {{ currentErrorIndex + 1 }} / 共 {{ errorQuestionCount }}
                <el-button @click="goToNextErrorQuestion" type="text" icon="el-icon-arrow-right"
                  style="color: red; padding-left: 5px;">
                  下一条
                </el-button>
              </span>
            </el-button>
          </div>



        </div>
        <div class="editable-container">
          <div class="editable-div scrollable-input">
            <div v-for="(question, index) in parsedQuestions" :key="index"
              :class="['parsed-question', { 'has-error': question.hasError }]">
              <p><strong>{{ index + 1 }}. 单选题</strong> {{ question.question }}</p>
              <div v-for="option in question.options" :key="option.key" class="option-item">
                <span class="option-label" :class="{ 'selected': option.key === question.answer }">

                </span>
                <span class="option-text">{{ option.key }}.{{ option.value }}</span>
              </div>
              <p>答案：{{ question.answer }}</p>
              <!-- 如果有错误，显示提示 -->
              <!-- 统一错误提示 -->
              <p v-if="question.hasError" style="color: red;">
                {{ question.errorMsg }}
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="bottom-content">
      <el-button type="primary" @click="handleAddQuestion" size="small">
        导入试题
      </el-button>
    </div>
    <update-chapter :show-dialog.sync="updateChapterShowDialog" :title="updateChapterdialogTitle" :fk_t_sctk_id="id"
      :chapters="chapters" @chapter-updated="handleChapterUpdated"></update-chapter>
  </div>
</template>
<script>
import { flattenChapters } from '@/utils'
import updateChapter from '@/components/updateChapter'
import { batchAddQuesstionBank } from '@/api/quesstionBank'
export default {

  name: 'batchExprotSctk',
  components: {
    updateChapter
  },
  props: {
    id: {
      type: Number,
      required: true,
    }, chapters: {
      type: Array,
      required: true
    }
  },

  watch: {
    // 编辑章节结束后刷新选择框数据
    updateChapterShowDialog(newVal) {
      if (!newVal) {
        this.$emit('refresh-chapters');
      }
    },

  },
  computed: {
    // 将嵌套数据转换为扁平数组
    flatChapters() {
      return flattenChapters(this.chapters);
    },
    // 输入题数
    totalQuestions() {
      return this.parsedQuestions.length;
    },
    // 错误题索引
    errorQuestionIndexes() {
      return this.parsedQuestions
        .map((q, index) => (q.hasError ? index : null))
        .filter(index => index !== null);
    },    // 错误题
    errorQuestionCount() {
      return this.parsedQuestions.filter(q => q.hasError).length;
    }
  },
  data() {
    return {
      type: '1',
      difficulty: '3',
      fk_t_sctk_chapter_id: '',
      chapterCheck: false,
      placeholderText: `
        1. 先查看格式说明后，再行录入
        2. 支持题型：单选
        3. 建议单次录入100-200题左右，方便检查
      `,
      isPlaceholderVisible: true, // 控制占位符显示状态
      textContent: '', // 用于保存输入内容
      parsedQuestions: [],
      updateChapterShowDialog: false,
      updateChapterdialogTitle: '编辑章节',
      currentErrorIndex: -1, // 当前显示的错误题索引

    }
  },
  methods: {

    handleChapterUpdated(newVal) {
      // 收到孙组件通知后，告诉父组件刷新数据
      if (!newVal) {
        this.$emit('refresh-chapters');
      }
    },
    editChapter() {
      //编辑章节
      this.updateChapterShowDialog = true
      this.updateChapterdialogTitle = '编辑章节'

    },
    async handleAddQuestion() {
      // 处理添加问题逻辑
      if (this.chapterCheck && !this.fk_t_sctk_chapter_id) {

        this.$message.warning('请选择章节');
        return
      }

      // 校验：检查 parsedQuestions 中是否有 hasError 为 true 的题目
      const invalidQuestions = this.parsedQuestions.filter(q => q.hasError);
      if (invalidQuestions.length > 0) {
        this.$message.error('存在格式错误的题目，请先去修正再提交');
        return; // 阻止提交
      }
      this.chapterCheck = this.chapterCheck ? 1 : 0;
      const params = {
        'parsedQuestions': this.parsedQuestions,
        'difficulty': this.difficulty,
        'fk_t_sctk_chapter_id': this.fk_t_sctk_chapter_id,
        'chapterCheck': this.chapterCheck,
        'fk_t_sctk_id': this.id,
        'type': this.type
      }

      await batchAddQuesstionBank(params)
      this.clearInput()
      this.$message.success('批量添加成功');

    },
    clearInput() {
      // 清空输入逻辑
      this.textContent = '';
      this.isPlaceholderVisible = true;

      // 更新 DOM 显示
      this.$refs.editableDiv.innerText = '';
      this.parsedQuestions = [];
      // this.isPlaceholderVisible = textContent.trim.length === 0;
    },
    // 自动识别格式
    autoFormat() {
      // 自动识别格式逻辑
      // 获取原始文本内容
      let originalText = this.textContent;

      // 替换所有的中文顿号 `、` 为英文句点 `.`
      const formattedText = originalText.replace(/、/g, '.');

      // 可选：更新输入框内容，让用户看到已格式化后的文本
      this.textContent = formattedText;
      console.log("传入 parseQuestions 的文本为：", formattedText);
      // 更新 div 显示内容
      // this.$refs.editableDiv.innerText = formattedText;

      const questions = this.parseQuestions(this.textContent);
      const correctedText = this.generateCorrectedText(questions);
      // 更新输入框内容，让用户看到已格式化后的文本
      this.textContent = correctedText;
      // 更新 div 显示内容
      this.$refs.editableDiv.innerText = correctedText;
      this.parsedQuestions = questions;
    },
    handleInput(event) {
      const inputText = event.target.innerText;
      // 更新响应式变量
      this.textContent = inputText;
      // 控制占位符是否显示
      this.isPlaceholderVisible = inputText.trim().length === 0;
      const questions = this.parseQuestions(this.textContent);
      this.parsedQuestions = questions;
      // this.autoFormat();
    },
    // 格式化题目
    parseQuestions(text) {
      const questions = [];
      const lines = text.split('\n').filter(line => line.trim() !== '');

      let currentQuestion = null;
      let options = [];

      // 正则匹配题目标号（1. 或 1、）
      const questionStartRegex = /^(\d+)[\.、]/;

      // 正则匹配选项标号（A. B. A、 B、）
      const optionStartRegex = /^([A-Za-z])[\.、]/;

      // 正则匹配答案行
      const answerStartRegex = /^答案[：:]/;

      lines.forEach((line, index) => {
        // 判断是否是一个新题目的开始
        if (questionStartRegex.test(line)) {
          if (currentQuestion) {
            this.finalizeQuestion(currentQuestion, options, questions);
          }
          currentQuestion = {
            topic: line.replace(questionStartRegex, '').trim(),
            options: [],
            answer: '',
          };
          options = [];
        }
        // 判断是否是选项
        else if (optionStartRegex.test(line)) {
          const match = line.match(optionStartRegex);
          const key = match[1].toUpperCase(); // 统一转为大写
          const value = line.slice(match[0].length).trim();
          options.push({ key, value });
        }
        // 判断是否是答案
        else if (answerStartRegex.test(line)) {
          const answer = line.replace(answerStartRegex, '').trim();
          if (currentQuestion) {
            currentQuestion.answer = answer;
            this.finalizeQuestion(currentQuestion, options, questions);
            currentQuestion = null;
          }
        }
        // 如果不是题头也不是选项也不是答案，则视为当前题目的内容补充（比如跨行题目描述）
        else if (currentQuestion && !answerStartRegex.test(line)) {
          currentQuestion.topic += '\n' + line.trim();
        }
      });

      // 处理最后一道题
      if (currentQuestion) {
        this.finalizeQuestion(currentQuestion, options, questions);
      }

      return questions;
    },
    // 处理每道题的错误信息
    finalizeQuestion(question, options, questions) {
      // 按照原始出现顺序排序选项
      // 映射成标准 A/B/C/D/E/F 的格式，保持选项内容顺序不变
      const correctedOptions = options.map((opt, idx) => ({
        key: String.fromCharCode(65 + idx), // A, B, C...
        value: opt.value,
      }));

      // 更新问题的选项
      question.options = correctedOptions;

      // 修正答案字段中的错误字母
      const answerChar = question.answer.charAt(0);
      const answerIndex = options.findIndex(opt => opt.key === answerChar);
      if (answerIndex !== -1) {
        question.answer = String.fromCharCode(65 + answerIndex); // 转换为正确的新字母
      }
      let errorMsg = '';
      let hasError = false;
      // 判断选项数量是否合法
      if (options.length < 2) {
        errorMsg = '选项数量不能少于 2 个';
        hasError = true;
      } else if (options.length > 6) {
        errorMsg = '选项数量不能多于 6 个';
        hasError = true;
      }
      // 验证答案是否有效
      const answer = question.answer.trim();

      if (!answer) {
        errorMsg = '答案不能为空，请填写正确答案。';
        hasError = true;
      } else {
        const validKeys = new Set(options.map(opt => opt.key.toUpperCase()));
        const answerKey = answer.toUpperCase();

        if (!validKeys.has(answerKey)) {
          errorMsg = '答案不在选项中，请检查答案是否正确。';
          hasError = true;
        }
      }

      // 设置统一错误信息
      question.hasError = hasError;
      question.errorMsg = errorMsg;
      // 添加进最终结果
      questions.push(question);
    },
    // 解析错误选项文本
    generateCorrectedText(questions) {
      return questions.map((question, questionIndex) => {
        const topicLine = `${questionIndex + 1}.${question.topic}`; // 恢复题目标号，如 1.题目内容
        const optionsText = question.options.map(opt => `${opt.key}.${opt.value}`).join('\n');
        return `${topicLine}\n${optionsText}\n答案:${question.answer}`;
      }).join('\n\n');
    },
    // 找到检查区错误代码
    scrollToErrorQuestion(indexInList) {
      const globalIndex = this.errorQuestionIndexes[indexInList];
      if (globalIndex === undefined) return;

      this.currentErrorIndex = indexInList;

      this.$nextTick(() => {
        // 假设你的题目容器是这个 class 名
        const container = document.querySelector('.editable-div'); // 替换为你实际的滚动容器
        const allQuestionEls = document.querySelectorAll('.parsed-question');

        if (allQuestionEls[globalIndex] && container) {
          const targetEl = allQuestionEls[globalIndex];

          // 使用 scrollIntoView 并指定容器
          targetEl.scrollIntoView({
            behavior: 'smooth',
            block: 'center'
          });

          // 高亮动画
          targetEl.style.transition = 'background-color 0.5s';
          targetEl.style.backgroundColor = '#ffe0e0';
          setTimeout(() => {
            targetEl.style.backgroundColor = '';
          }, 1000);
        }
      });
    },

    goToNextErrorQuestion() {
      if (this.errorQuestionCount === 0) return;

      let nextIndex = this.currentErrorIndex + 1;

      // 如果已经是最后一条，跳回第一条
      if (nextIndex >= this.errorQuestionCount) {
        nextIndex = 0;
      }

      this.scrollToErrorQuestion(nextIndex);
    }

  }
}
</script>
<style scoped>
.app-container {
  background: #fff;
  display: flex;
  border-radius: 5px;
  flex-direction: column
}

.content {
  height: 50px;
}

.top-content {
  display: flex;
  align-items: center;
}

/* 每个搜索组 */
.search-group {
  display: flex;
  align-items: center;
  /* 垂直对齐 */
  /**
   width: calc(20% - 10px);
   */
  margin-right: 30px;
  /* 每行放两个 */
}

.search-label {
  font-size: 12px;
  margin-top: 10px;
  color: #606266;
  /* 防止文字换行 */
}

.search-item {
  flex: 1;
  width: 150px;
  /* 输入框占据剩余空间 */
  height: 20px;
  line-height: 20px;
  font-size: 12px;

}

.search-item2 {
  flex: 1;
  width: 200px;
  /* 输入框占据剩余空间 */
  height: 20px;
  line-height: 20px;
  font-size: 12px;

}

/* 按钮组样式 */
.action-buttons {
  display: flex;
  margin-top: 10px;
  align-items: center;
  gap: 5px;
  /* 按钮之间的间距 */
  width: auto;
  /* 自适应宽度 */
}

.action-buttons-wrapper {
  position: relative;
  /* 作为定位参考点 */
  margin-top: 10px;
}

.import-button {
  position: absolute;
  top: 0;
  right: -800px;
  /* 贴靠右侧对齐 */
  z-index: 10;
  /* 确保在其他内容之上 */
}

.main-content {
  display: flex;
  margin-top: 10px;

}

/* 内容区 */


.input-area {
  border: 1px solid #ededed;
  width: 50%;
  height: 600px;
  margin-right: 20px;
}

.toolbar {
  /* background-color: #f3f3f5;
  border: 1px solid #eeeeee;
  padding: 0 5px 0 10px;
  height: 37px; */
  display: flex;
  align-items: center;
  justify-content: flex-start;
  /* 左对齐 */
  background-color: #f3f3f5;
  border: 1px solid #eeeeee;
  padding: 0 5px 0 10px;
  height: 37px;
}

.toolbar-separator {
  display: flex;
  align-items: center;
  overflow: hidden;
  /* 防止内容溢出 */
  white-space: nowrap;
  /* 防止换行 */
  gap: 10px;
  margin-left: 100px;
  /* 按钮之间的间距 */
}

.toolbar-separator .el-button {
  margin-right: 5px;
  /* 添加右边距 */
}

.editable-container {
  position: relative;
  width: 100%;
  height: calc(100% - 37px);
  /* 减去 toolbar 的高度 */
  overflow: hidden;
  /* 防止内容溢出 */
}

.editable-div {
  min-height: 100px;
  /* border: 1px solid #ccc; */
  padding: 20px;
  font-size: 14px;
  color: #333;
  white-space: pre-wrap;
  outline: none;
  overflow-y: auto;
  /* ✅ 正确做法 */
  height: 100%;
  /* 限制高度以出现滚动条 */
}

.placeholder-text {
  position: absolute;
  top: 5px;
  left: 5px;
  color: #999;
  opacity: 0.7;
  pointer-events: none;
  white-space: pre-wrap;
}

/* 检查区 */
.parsed-question {
  display: block;
  overflow: hidden;
  margin-bottom: 20px;
  border: 1px solid #ddd;
  padding: 10px;
  border-radius: 5px;
  background-color: #f9f9f9;
}

.parsed-question.has-error {
  border-color: red;
  background-color: #fff0f0;
  /* 可选：加个浅红背景更明显 */
}

.parsed-question p,
.option-item span {
  white-space: pre-wrap;
  word-break: break-word;
}

.parsed-question p {
  margin: 5px 0;
  font-size: 14px;
  color: #333;
}

.option-item {
  display: flex;
  align-items: flex-start;
  gap: 10px;
  margin: 6px 0;
  font-size: 14px;
  color: #555;
}

.option-label {
  flex-shrink: 0;
  width: 20px;
  height: 20px;
  border: 1px solid #ccc;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: normal;
  margin-top: 2px;
}

.option-label.selected {
  background-color: #1a73e8;
  border-color: #1a73e8;
  color: white;
  font-weight: bold;
}

.option-text {
  flex-grow: 1;
  white-space: pre-wrap;
  word-break: break-word;
}

.scrollable-input {
  overflow-y: auto;
  /* 当内容超出时显示滚动条 */
  max-height: 600px;
  /* 设置最大高度，可以根据需要调整 */
}

.bottom-content {
  margin-top: 10px;
}
</style>
